package cd.zhixuan.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

import cd.zhixuan.utils.dialog.Toaster;

/**
 * @author CHAO
 * Create Time: 2021.12.30 14:51
 **/
public final class GlobalTools {

    private static Context mContext;

    /**
     * 在Application初始化时调用
     *
     * @param context application
     */
    public static void init(Context context) {
        mContext = context;
        if (mContext instanceof Application) {
            //注册全局activity状态监听
            ((Application) mContext).registerActivityLifecycleCallbacks(new OnActivityLifecycleCallbacks());
        }
    }

    public static Context getContext() {
        return mContext;
    }


    @Nullable
    private static WeakReference<Activity> CURRENT_ACTIVITY;

    @Nullable
    public static Activity getCurrentActivity() {
        WeakReference<Activity> current = CURRENT_ACTIVITY;
        if (current == null) return null;
        return current.get();
    }

    /**
     * activity状态统一监听
     */
    private static final class OnActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            CURRENT_ACTIVITY = new WeakReference<>(activity);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {

        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {

        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
            Toaster.destroyActiveToast();
        }
    }
}
